import { Colors } from "./color";
import DataBus from './databus';
import * as THREE from 'three';

const databus = new DataBus()
const game = databus.game


// 创建云
class Cloud {
	constructor() {
		this.mesh = null; // 实例

		this.draw()
	}

	// 云的旋转
	rotate() {
		this.mesh.children.forEach((m, i) => {
			m.rotation.z += Math.random() * .005 * (i + 1);
			m.rotation.y += Math.random() * .002 * (i + 1);
		})
	}

	draw() {
		this.mesh = new THREE.Object3D();
		this.mesh.name = "cloud";
		const geom = new THREE.CubeGeometry(20, 20, 20);
		const mat = new THREE.MeshPhongMaterial({
			color: Colors.white,
		});

		//* 一团云3-5个方块
		const nBlocs = 3 + Math.floor(Math.random() * 3);
		for (let i = 0; i < nBlocs; i++) {
			const m = new THREE.Mesh(geom.clone(), mat);
			m.position.x = i * 15; // 一块云x轴差15
			m.position.y = Math.random() * 10;
			m.position.z = Math.random() * 10;
			m.rotation.z = Math.random() * Math.PI * 2;
			m.rotation.y = Math.random() * Math.PI * 2;
			const s = .1 + Math.random() * .9; // 缩放 0.1-1
			m.scale.set(s, s, s);
			this.mesh.add(m);
			m.castShadow = true;
			m.receiveShadow = true;
		}
	}
}

// 创建天空
export default class Sky {
	constructor() {
		this.mesh = new THREE.Object3D(); // 实例
		this.nClouds = 20; // 20，云的数量
		this.clouds = []; // 所有云的实例集合

		this.draw()
	}

	draw() {
		const stepAngle = Math.PI * 2 / this.nClouds;
		for (let i = 0; i < this.nClouds; i++) {
			const c = new Cloud();
			this.clouds.push(c);
			const a = stepAngle * i; // 0至π
			const h = game.seaRadius + 150 + Math.random() * 200;
			// 设置云的位置、角度、缩放
			c.mesh.position.y = Math.sin(a) * h;
			c.mesh.position.x = Math.cos(a) * h;
			c.mesh.position.z = -300 - Math.random() * 500;
			c.mesh.rotation.z = a + Math.PI / 2;
			const s = 1 + Math.random() * 2;
			c.mesh.scale.set(s, s, s);
			this.mesh.add(c.mesh); // 添加云
		}
		this.mesh.position.y = -game.seaRadius;
	}

	update() {
		Array.from(Array(this.nClouds), (_, i) => this.clouds[i].rotate()); // 云旋转
		// 云向后移动
		this.mesh.rotation.z += game.speed;
	}
}